package com.zbb.exam_system.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.zbb.exam_system.constant.Method;
import com.zbb.exam_system.dto.JsonResult;
import com.zbb.exam_system.dto.TableDto;
import com.zbb.exam_system.entity.Student;
import com.zbb.exam_system.entity.Teacher;
import com.zbb.exam_system.exception.ExamException;
import com.zbb.exam_system.service.UserService;
import com.zbb.exam_system.utils.HttpUtils;
import com.zbb.exam_system.vo.StudentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @author zbbstart
 * @date 2021/2/10 - 10:08
 */
@RestController
@RequestMapping("students")
@Slf4j
@Api(tags = "学生管理功能的相关接口")
public class StudentManagerController {
    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private UserService userService;

    /**
     * 获取所有的学生
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @ApiOperation(value = "获取所有的学生", notes = "获取角色为老师的所有的用户")
    public JsonResult getAllStudents(@ApiParam(name = "token", example = "") @RequestHeader("auth-token") String token, HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            int pageNo = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("limit"));
            log.info("当前学生页码:" + pageNo);
            log.info("页面限制的条数:" + pageSize);
            TableDto tableDto = userService.getAllStudentUsersByPage(pageNo, pageSize, token);
            log.info("渲染学生表格的信息:" + tableDto);
            result = httpUtils.buildSuccess(Method.GET, tableDto);
        } catch (ExamException ee) {
            result = httpUtils.buildFailure(ee.getMessage(), Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 新增学生
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @PostMapping
    @ApiOperation(value = "新增学生", notes = "登录身份是管理员，为学生选择系统中已有的老师")
    public JsonResult addStudent(@RequestBody StudentVo studentVo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            userService.insertStudentUser(studentVo);
            result = httpUtils.buildSuccess(Method.POST, "添加成功...");
        }catch (ExamException e){
            result = httpUtils.buildFailure(e.getMessage(), Method.GET);
        }catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 修改学生的信息
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @PutMapping("{studentNo}")
    @ApiOperation(value = "修改学生的信息", notes = "登录身份是管理员，修改学生的所有信息，登录身份是老师，不能修改所属老师这一信息")
    public JsonResult updateStudent(@ApiParam(name = "token", example = "") @RequestHeader("auth-token") String token,
                                    @PathVariable("studentNo") Integer studentNo,
                                    @RequestBody StudentVo studentVo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            studentVo.setStudentNo(studentNo);
            userService.updateStudentUserInfo(studentVo, token);
            result = httpUtils.buildSuccess(Method.POST, "修改成功...");
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 获取当前学生的老师信息
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER','ROLE_STUDENT')")
    @GetMapping("{studentNo}")
    @ApiOperation(value = "获取当前学生的老师信息", notes = "根据学生的编号获取当前学生的老师信息")
    public JsonResult getTeacherInfo(@PathVariable("studentNo") Integer studentNo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            Teacher teacher = userService.getteacherInfoByStudentNo(studentNo);
            result = httpUtils.buildSuccess(Method.GET, teacher);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 删除学生
     * 可以是单个学生的删除，也可以是多个学生的删除
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER','ROLE_STUDENT')")
    @DeleteMapping
    @ApiOperation(value = "删除学生", notes = "根据前端传来的学生编号删除学生")
    public JsonResult deleteUser(@RequestParam("studentNos") List<Integer> studentNos, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        log.info("删除学生用户的编号:" + Arrays.toString(studentNos.toArray()));
        try {
            userService.deleteStudentUsers(studentNos);
            result = httpUtils.buildSuccess(Method.DELETE);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

}
